package cn.mastor.basic.util;


import cn.mastor.basic.config.BussinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

public class MailUtil {
    ApplicationContext context = SpringUtil.getContext();
    JavaMailSender sender = context.getBean(JavaMailSender.class);
    MimeMessage mimeMessage = sender.createMimeMessage();
    // 2.发送复杂邮件的工具类
    MimeMessageHelper helper = null;
    public void sendMail(String FromMail,String toMail, String subject,
                            String text,Boolean ishtml){
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom(FromMail);
            helper.setSubject(subject);
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText(text,ishtml);
            // 5.设置收件人
            helper.setTo(toMail);
        } catch (Exception e) {
            throw new BussinessException("发送邮件错误！");
        }
        // 6.发送邮件
        sender.send(mimeMessage);

    }
}
